//
//  GQHSettingsController.m
//  Xanthium
//
//  Created by GuanQinghao on 01/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model

#pragma mark Object

#pragma mark View
#import "GQHSettingsView.h"

#pragma mark Controller
#import "GQHSettingsController.h"
#import "GQHMobileController.h"
#import "GQHAboutController.h"
#import "GQHLoginController.h"
#import "ClipViewController.h"

#pragma mark CocoaPods
#import <TZImagePickerController.h>

#pragma mark ----------Header End----------

@interface GQHSettingsController () <GQHSettingsViewDelegate,TZImagePickerControllerDelegate, ClipPhotoDelegate> {
    
#pragma mark Data
    /// 头像参数
    NSMutableDictionary *parameters;
#pragma mark View
    /// 自定义根视图
    GQHSettingsView *rootView;
}

@end


@implementation GQHSettingsController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHSettingsView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    rootView.appVersion = [self.appVersion stringByReplacingOccurrencesOfString:@"V" withString:@""];
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    parameters = [NSMutableDictionary dictionary];
    [parameters setObject:USER_GET_ID forKey:@"userId"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_titleLabel.text = @"设置";
    self.qh_rightButton.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
}

#pragma mark --Delegate
- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
            
        case 0: {
            
            // 查看/修改头像
            TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            [imagePickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                DLog(@"选择图片完成,上传图片");
                
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                    ClipViewController *viewController = [[ClipViewController alloc] init];
                    viewController.image = [photos firstObject];
                    //         viewController.picker = _imgPicker;
                    viewController.controller = self;
                    viewController.delegate = self;
                    viewController.isTakePhoto = YES;
                    [self presentViewController:viewController animated:YES completion:nil];
//                });
            }];
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
            break;
        case 1: {
            
            // 修改手机号
            GQHMobileController *mobileController = [[GQHMobileController alloc] init];
            mobileController.qh_identifierType = @"mobile";
            mobileController.qh_mobile = USER_GET_MOBILE;
            mobileController.qh_done = NO;
            mobileController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mobileController animated:YES];
        }
            break;
        case 2: {
            
            // 修改密码
            GQHMobileController *mobileController = [[GQHMobileController alloc] init];
            mobileController.qh_identifierType = @"password";
            mobileController.qh_mobile = USER_GET_MOBILE;
            mobileController.qh_done = NO;
            mobileController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:mobileController animated:YES];
        }
            break;
        case 4: {
            
            // 关于我们
            GQHAboutController *aboutController = [[GQHAboutController alloc] init];
            aboutController.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:aboutController animated:YES];
        }
            break;
        case 5: {
            
            // 退出登录
            [self qh_alertWithTitle:@"您是否确认退出当前帐号?" message:nil actionTitle:@"退出" handler:^(UIAlertAction *action) {
                
                GQHLoginController *loginController = [[GQHLoginController alloc] init];
                UINavigationController *loginNavController = [[UINavigationController alloc] initWithRootViewController:loginController];
                [[UIApplication sharedApplication] keyWindow].rootViewController = loginNavController;
            } completion:nil];
        }
            break;
        default:
            break;
    }
}

/**  获取裁剪后的图片  */
- (void)clipPhoto:(UIImage *)image
{
    GQH_WEAKSELF;
    if (image) {
        
        [weakSelf uploadImage:image success:^(NSNumber *code, NSString *message, NSString *data) {
            
            if (0 == [code integerValue]) {
                
                [[NSUserDefaults standardUserDefaults] setObject:data forKey:USER_AVATAR];
                [rootView.qh_tableView reloadData];
                
                [self showToastWithText:message];
            }
        }];
    }
}

#pragma mark --TargetMethod

#pragma mark --PrivateMethod
/// 上传头像图片
- (void)uploadImage:(UIImage *)image success:(void(^)(NSNumber *code, NSString *message, NSString *data))success {
    
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/loginRegist/1/replaceHead"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manager POST:APIURLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImagePNGRepresentation(image);
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmssSSS";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        [formData appendPartWithFileData:data name:@"headImg" fileName:fileName mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            
            NSNumber *responseCode = [responseObject objectForKey:@"code"];
            NSString *responseMessage = [responseObject objectForKey:@"msg"];
            NSString *responseData = [responseObject objectForKey:@"data"];
            
            success(responseCode,responseMessage,responseData);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View

@end
